#!/usr/bin/env php
<?php
//declare(ticks = 1);

// Only for cli.
use Wing\Library\Worker;

if (PHP_SAPI !== 'cli') {
    exit("Only run in command line mode \n");
}
if (!function_exists("socket_create")) {
    exit("Please install php_sockets extension \n");
}

//定义时间区
date_default_timezone_set("PRC");
//strtoupper(substr(PHP_OS, 0, 3))==='WIN' || "CYGWIN" == PHP_OS
define('IS_WINDOWS', DIRECTORY_SEPARATOR === '\\');
//根目录
define("HOME", __DIR__);

//初始化日志目录
if (!is_dir(__DIR__."/logs")) {
    mkdir(__DIR__."/logs");
}

//初始化命令行参数 $argc — 传递给脚本的参数数目
$str_argv = '';
for ($i = 1; $i < $argc; $i++) {
    $str_argv .= ' '.$argv[$i];
}

$command_line = 'php '.basename(__FILE__).' '.$str_argv;
define("WING_COMMAND_LINE", $command_line);

if (!file_exists(__DIR__."/composer.json")) {
    copy(__DIR__."/composer.json.init", __DIR__."/composer.json");
}

if (!file_exists(__DIR__.'/vendor/autoload.php')) {
    echo "正在尝试安装依赖-composer install", PHP_EOL;
    exec("composer install");
}

require __DIR__.'/vendor/autoload.php';

$action = isset($argv[1]) ? $argv[1] : '';
$daemon = array_search('-d', $argv) ? true : false;
$workers = 1;
$n_key = array_search('-n', $argv);
if($n_key && isset($argv[$n_key+1]) && is_numeric($argv[$n_key+1])){
    $workers = (int)$argv[$n_key+1];
}

define("WING_DEBUG", !$daemon);
if (WING_DEBUG) {
    ini_set("display_errors", "On");
    error_reporting(E_ALL);
}


if(!in_array($action, ['start','restart','stop','status'])){
    $action = '';
}
$runLock = __DIR__ . '/runLock'; //防重复运行
if($action=='start'){
    if(is_file($runLock) && file_get_contents($runLock)==1){
        echo 'wing is running!',PHP_EOL;
        exit(0);
    }
}
elseif($action=='restart'){
    Worker::stopAll();
}elseif($action=='stop'){
    file_put_contents($runLock, 0);
    Worker::stopAll();
    exit(0);
}elseif($action=='status'){
    Worker::showStatus();
    sleep(1);
    echo file_get_contents(HOME."/logs/status.log");
    exit(0);
}else{
    echo "执行 php wing start|restart|stop|status, [start|restart]可选参数 -d 以守护进程执行, -n 指定进程数量".PHP_EOL;
    echo "如： php wing start -d -n 8".PHP_EOL;
    exit(0);
}

file_put_contents($runLock, 1);
$worker = new Worker([
    "daemon"  => !!$daemon,
    "workers" => $workers
]);
$worker->start();